package com.kcyu.sfhinvoice.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.kcyu.sfhinvoice.domain.User;
import com.kcyu.sfhinvoice.dto.ChangePasswordDTO;
import com.kcyu.sfhinvoice.dto.LoginDTO;
import com.kcyu.sfhinvoice.enums.UserStatusEnums;
import com.kcyu.sfhinvoice.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sys")
@Slf4j
@Api(tags = "系统管理")
public class SysController {

    @Autowired
    private UserService userService;

    @PostMapping("login")
    @ApiOperation(value = "登录")
    public SaResult doLogin(@RequestBody LoginDTO loginDTO) {
        User login = userService.login(loginDTO);
        if(login != null) {
            if(login.getRole().equals("开票员")) {
                JSONArray jsonArray = JSONUtil.parseArray(login.getSellerRole());
                List<String> list1 = JSONUtil.toList(jsonArray, String.class);
                login.setSellerRoleList(list1);
            }
            return SaResult.data(login);
        } else {
            return SaResult.error("登录失败");
        }
    }

    @GetMapping("isLogin")
    @ApiOperation("检测是否登录")
    public SaResult isLogin() {
        StpUtil.checkLogin();
        return SaResult.ok();
    }

    @GetMapping("getCurrentUser")
    @ApiOperation("获取当前登录用户")
    public SaResult getCurrentUser() {
        int loginIdAsInt = StpUtil.getLoginIdAsInt();
        if (loginIdAsInt == 999) {
            User developUser = userService.getDevelopUser();
            return SaResult.data(developUser);
        }
        User user = new User().selectById(loginIdAsInt);
        if(user.getRole().equals("开票员")) {
            JSONArray jsonArray = JSONUtil.parseArray(user.getSellerRole());
            List<String> list1 = JSONUtil.toList(jsonArray, String.class);
            user.setSellerRoleList(list1);
        }
        user.setPassword(null);
        return SaResult.data(user);
    }

    @PostMapping("logout")
    @ApiOperation(value = "登出")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok("登出成功");
    }

    @GetMapping("getCaptcha")
    @ApiOperation(value = "获取验证码")
    public void getCaptcha(HttpServletResponse response) {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        lineCaptcha.setGenerator(new RandomGenerator("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 2));
        lineCaptcha.createCode();
        try {
            log.info("验证码：{}", lineCaptcha.getCode());
            lineCaptcha.write(response.getOutputStream());
        } catch (IOException e) {
            response.setStatus(500);
            throw new RuntimeException(e);
        }
    }

    @PostMapping("addUser")
    @ApiOperation(value = "添加用户")
    public SaResult addUser(@RequestBody User user) {
        if(user.getRole().equals("开票员")) {
            user.setSellerRole(JSONUtil.toJsonStr(user.getSellerRoleList()));
        }
        User user1 = userService.addUser(user);
        return SaResult.data(user1);
    }

    @PostMapping("register")
    @ApiOperation(value = "注册")
    public SaResult register(@RequestBody User user) {
        boolean register = userService.register(user);
        return SaResult.data(register);
    }

    @PostMapping("changePassword")
    @ApiOperation(value = "修改密码")
    public SaResult changePassword(@RequestBody ChangePasswordDTO changePasswordDTO) {
        boolean b = userService.changePassword(changePasswordDTO);
        return SaResult.data(b);
    }

    @PostMapping("update")
    @ApiOperation(value = "添加/修改用户")
    public SaResult update(@RequestBody User user) {
        user.setPassword(null);
        if(user.getRole().equals("开票员")) {
            user.setSellerRole(JSONUtil.toJsonStr(user.getSellerRoleList()));
        } else {
            user.setSellerRole(null);
        }
        boolean b = userService.updateById(user);
        return SaResult.data(b);
    }

    @PostMapping("deleteUser")
    @ApiOperation(value = "删除用户")
    public SaResult deleteUser(@RequestParam("id") String id) {
        boolean b = userService.removeById(id);
        if(b) {
            return SaResult.ok("操作成功");
        } else {
            return SaResult.error("操作失败");
        }
    }

    @PostMapping("resetPassword")
    @ApiOperation(value = "重置密码")
    public SaResult resetPassword(@RequestParam("id") String id) {
        boolean b = userService.resetPassword(id);
        if(b) {
            return SaResult.ok("操作成功");
        } else {
            return SaResult.error("操作失败");
        }
    }

    @PostMapping("activeAccount")
    @ApiOperation(value = "更改密码激活账号")
    public SaResult activeAccount(@RequestBody Map<String, String> map) {
        String password = map.get("password");
        int loginIdAsInt = StpUtil.getLoginIdAsInt();
        User user = new User().selectById(loginIdAsInt);
        if(user.getStatus() != UserStatusEnums.INIT) {
            return SaResult.error("该账号已激活，不允许再次激活");
        }

        user.setStatus(UserStatusEnums.NORMAL);
        user.setPassword(password);
        user.updateById();
        return SaResult.ok();
    }


    @PostMapping("list")
    @ApiOperation(value = "查询用户列表")
    public SaResult list() {
        List<User> list = userService.list();
        list.forEach(each -> {
            each.setPassword(null);
            if (each.getRole().equals("开票员")) {
                JSONArray jsonArray = JSONUtil.parseArray(each.getSellerRole());
                List<String> list1 = JSONUtil.toList(jsonArray, String.class);
                each.setSellerRoleList(list1);
            }
        });
        return SaResult.data(list);
    }

    @Value("${running-profile}")
    private String Environment;

    @GetMapping("getLog")
    @ApiOperation(value = "获取操作日志")
    public SaResult getLog() {
        String filePath = null;
        if(Environment.equals("dev")) {
            filePath = "D:\\logs\\heartbreak.log";
        } else {
            filePath = "/data/sfh-invoice/heartbreak.log";
        }

        try (RandomAccessFile raf = new RandomAccessFile(filePath, "r")) {
            long length = raf.length();
            long pointer = length - 1;
            int lineCount = 0;
            StringBuilder lastHundredLines = new StringBuilder();

            while (pointer >= 0 && lineCount < 100) {
                raf.seek(pointer);
                char c = (char) raf.read();
                if (c == '\n') {
                    lineCount++;
                }
                lastHundredLines.insert(0, c);
                pointer--;
            }

            return SaResult.data(new String(lastHundredLines.toString().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
